package edu.berkeley.drivingbuddy;


import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import com.androidplot.series.XYSeries;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;

public class Goals  extends Activity {//implements TextWatcher{
    
    EditText goalEditText;
    TextView feedback;
    int maxAttemptIndex = 0;
    int[] colors = { Color.BLUE, Color.RED, Color.YELLOW,Color.CYAN, Color.MAGENTA, Color.WHITE, Color.GRAY};
    private XYPlot progessPlot;
    List<XYSeries> courses2 = new LinkedList<XYSeries>();
    List<Integer> mostRecentScores = new LinkedList<Integer>();
    SeekBar goalSeek;
    TextView goalScoreLabel;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goal);

        feedback = (TextView) findViewById(R.id.label_feedback);
        goalScoreLabel = (TextView) findViewById(R.id.label_goalscore);
        //score input
//        goalEditText = (EditText) findViewById(R.id.goal_edit_text);
//        goalEditText.addTextChangedListener(this);
//        goalEditText.setText("" + DrivingBuddy.getDatastore().getGoalScore());
        
        goalSeek = (SeekBar) findViewById(R.id.goal_seekbar);
        goalSeek.setProgress(DrivingBuddy.getDatastore().getGoalScore());
        goalSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                goalScoreLabel.setText("  " + goalSeek.getProgress());
                getScoreAndPlot2();
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        goalScoreLabel.setText("  " + goalSeek.getProgress());
     
        progessPlot = (XYPlot) findViewById(R.id.goal_result1);
        getGraphData2();
        getScoreAndPlot2();
    }

    private void getGraphData2() {
        List<ResultGroup> resultGroups = DrivingBuddy.getDatastore().getResultGroups();
        for (ResultGroup rg : resultGroups) {
            List<ResultObj> results = rg.getResults();
            List<Integer> values = new LinkedList<Integer>();
            for (ResultObj r : results ) {
//                values.add((int)r.getTime());
                values.add(r.getScore());
            }
            mostRecentScores.add(results.get(results.size()-1).getScore());
            courses2.add(new SimpleXYSeries(values, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, rg.getName()));
            maxAttemptIndex = Math.max(maxAttemptIndex,results.size());
        }
        
    }
    
    
    private void getScoreAndPlot2() {
        if (progessPlot != null) {
            double goalScore = DrivingBuddy.getDatastore().getGoalScore();
            goalScore = goalSeek.getProgress();

            Number[] series1Numbers = { 0, goalScore, maxAttemptIndex-1, goalScore };
            progessPlot.clear();
            XYSeries goal = (new SimpleXYSeries(Arrays.asList(series1Numbers), SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED, "Goal"));
            progessPlot.addSeries(goal, new LineAndPointFormatter(Color.GREEN, Color.GREEN, null));

            int colorIndex = 0;
            for (XYSeries s : courses2) {
                progessPlot.addSeries(s, new LineAndPointFormatter(colors[colorIndex], colors[colorIndex], null));
                colorIndex = (colorIndex + 1) % colors.length;
            }
            progessPlot.setRangeBoundaries(0, 100, BoundaryMode.FIXED);

            // Reduce the number of range labels
            progessPlot.setTicksPerRangeLabel(2);
            progessPlot.setDomainStep(XYStepMode.SUBDIVIDE, maxAttemptIndex-1);
            progessPlot.setDomainLabel("Attempt Number");
            progessPlot.setRangeLabel("Score");

            // By default, AndroidPlot displays developer guides to aid in
            // laying out your plot.
            // To get rid of them call disableAllMarkup():
            progessPlot.disableAllMarkup();
            progessPlot.invalidate();
            
            int good = 0;
            for (Integer score : mostRecentScores) {
                if (score > goalScore) {
                    good++;
                }
            }
            String f;
            if (good == 1) {
                f = String.format("%d of your most recent attempts is above your goal.", good);   
            } else {
                f = String.format("%d of your most recent attempts are above your goal.", good);
            }
            if ((good/(mostRecentScores.size()+0.1)) > 0.50) {
                f += " Good Job!";
            }else {
                f += " Try Harder!";
            }
            feedback.setText(f);
        }
    }

//    @Override
//    public void afterTextChanged(Editable s) {
//    }
//
//    @Override
//    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//    }
//
//    @Override
//    public void onTextChanged(CharSequence s, int start, int before, int count) {
//        double score = .parseDouble(goalEditText.getText().toString());
//        DrivingBuddy.getDatastore().setGoalScore(score);
//        getScoreAndPlot2();
//    }
}

